<!-- PayList 支付列表 -->
<template>
  <view class="PayList" v-if="show">
    <view class="title" v-if="title && list.length">{{ title }}</view>
    <pay-item
      @click.native="handleClick(item)"
      v-for="(item, index) in list"
      :key="index"
      class="zm-bor-b"
      :title="item.name"
      :img="item.image"
      :desc="item.describe"
      :check="item.type === check"
      :has-check="hasCheck"
    />

    <other-popup @surePay="handlePay" v-model="visible" :pay-data="payData" />
  </view>
</template>

<script>
  import PayItem from './PayItem'
  // #ifdef H5
  import * as wxSdk from '@/utils/sdk/src/wx.js'
  // #endif
  import OtherPopup from './OtherPopup'
  export default {
    name: 'pay-list',
    components: { PayItem, OtherPopup },
    props: {
      title: {
        type: String,
        default: '收银台'
      },
      value: {
        type: String,
        required: true
      },
      query: {
        type: Object
      },
      // film 影票支付cardRecharge 电影卡充值  mall 商城 goods卖品 accoutRecharge账户充值
      orderType: {
        type: String,
        required: true
      },
      hasCheck: {
        type: Boolean,
        default: true
      },
      urlQuery: {
        type: Object,
        default: () => {
          return {}
        }
      },
      list: {
        type: Array,
        default: []
      }
    },
    computed: {
      show: {
        set(v) {
          this.$emit('input', v)
        },
        get() {
          if (this.value) {
            this.init()
          }
          return this.value
        }
      }
    },
    data() {
      return {
        // list: [],
        check: '', // 支付方式 payType
        tradeType: 'JSAPI',
        visible: false,
        payData: {}
      }
    },
    // created() {
    //   this.init()
    // },
    methods: {
      // 初始化方法
      init() {
        // this.getList()
      },
      getList() {
        const query = this.query
        const data = {
          orderType: this.orderType,
          // activityId: this.activityId,
          zoneId: query.zoneId,
          cinemaId: query.cinemaId
        }
        uni.$api.mall.getPayWay(data).then((res) => {
          this.list = res
          if (this.list.length === 1) {
            this.check = this.list[0].type
            this.$nextTick(() => {
              // 只有一种支付方式
              console.log('只有一种支付')
              this.$emit('hasOnePay')
            })
          } else {
            console.log('有多种种支付')
            this.$emit('hasMorePay')
          }
        })
      },
      handleClick(item) {
        if (this.hasCheck) {
          this.check = item.type
        }
        this.$emit('payType', item.type)
      },

      getPayType() {
        const check = this.check
        if (check) {
          return Promise.resolve(check)
        }
        this.$msg.toast('请选择支付方式')
        return Promise.reject({ msg: '未选中支付方式' })
      },

      // 获取支付参数
      createOrderPay(query = {}, url = '') {
        // url = url || window.location.href
        // const vuePath = url.split('#')[1] || ''
        // const joinStr = vuePath.includes('?') ? '&' : '?'
        // let urlQuery = this.$utils.obj2Param({
        //   ...this.urlQuery,
        //   ...{ myPayToken: auth.getLocToken() }
        // })
        // urlQuery = urlQuery ? '&' + urlQuery : ''
        // url = `${url}${joinStr}hasPay=1` + urlQuery
        // url = this.$utils.handleUrl(url)
        // console.log(url)
        let tradeType = 'JSAPI'
        if (
          this.$auth.platform() === 'mp-alipay' ||
          this.$auth.platform() === 'mp-toutiao'
        ) {
          tradeType = 'xcx'
        } else if (this.$auth.platform() === 'mp-weixin') {
          tradeType = 'JSAPI'
        }
        let data = {
          payType: this.check,
          orderType: this.orderType,
          tradeType: tradeType,
          orderId: '', // 订单id   *
          payMoney: '' // 需要支付的钱 *
          // frontUrl: url,
          // url: window.location.href,
          // activityId: this.activityId
        }
        query = this.$utils.deep(query)
        data = { ...data, ...query }
        console.log(data)
        return uni.$api.pay.createOrderPay(data).then((res) => {
          const resData = res

          if (resData.payPopup) {
            this.payData = resData
            this.visible = true

            return Promise.reject({ myMsg: '二次弹窗' })
          }
          return this.handlePay(resData)
        })
      },

      handlePay(data) {
        console.log('paydata', data)

        // #ifdef MP-TOUTIAO
        const douyinData = data.douyinpay
        uni.requestPayment({
          orderInfo: douyinData,
          service: 5,
          getOrderStatus: (res) => {
            console.log('getOrderStatus res', res)
            if (res.code === 4) {
              this.$msg.toast('取消支付')
              const fromPath = this.$tools.getCurrentPage().fromPath
              if (fromPath === 'pagesOrder/sureOrder/index') {
                uni.setStorageSync('payIndex', '1')
                this.$tools.navigateTo(-1)
              } else if (fromPath === 'pagesOrder/goodsPay/index') {
                console.log('取消支付')
                this.$tools.navigateTo(
                  '/pagesOrder/order/detail',
                  {
                    orderId: data.orderId,
                    type: this.orderType
                  },
                  'redirectTo'
                )
              } else if (fromPath === 'pagesOrder/order/detail') {
                this.$tools.navigateTo(-1)
              } else {
                this.$tools.navigateTo('/pagesOrder/order/detail', {
                  orderId: data.orderId,
                  type: this.orderType
                })
              }
            } else if (res.code === 0) {
              // 支付成功跳转
              console.log(res, 'res')
              this.$emit('paySuccess')
            } else {
              this.$msg.toast('支付失败', res)
              this.$tools.navigateTo('/pagesOrder/payError/index')
            }
          },

          success: (res) => {
            //抖音支付成功
            console.log('res', res)
            if (res.code === 4) {
              this.$msg.toast('取消支付')
              const fromPath = this.$tools.getCurrentPage().fromPath
              if (fromPath === 'pagesOrder/sureOrder/index') {
                uni.setStorageSync('payIndex', '1')
                this.$tools.navigateTo(-1)
              } else if (fromPath === 'pagesOrder/goodsPay/index') {
                console.log('取消支付')
                this.$tools.navigateTo(
                  '/pagesOrder/order/detail',
                  {
                    orderId: data.orderId,
                    type: this.orderType
                  },
                  'redirectTo'
                )
              } else if (fromPath === 'pagesOrder/order/detail') {
                this.$tools.navigateTo(-1)
              } else {
                this.$tools.navigateTo('/pagesOrder/order/detail', {
                  orderId: data.orderId,
                  type: this.orderType
                })
              }
            } else if (res.code === 0) {
              // 支付成功跳转
              console.log(res, 'res')
              this.$emit('paySuccess')
            } else {
              this.$msg.toast('支付失败', res)
              this.$tools.navigateTo('/pagesOrder/payError/index')
            }
          },
          fail: (err) => {
            console.log('err', err)
            this.$msg.toast('支付失败', err)
            this.$tools.navigateTo('/pagesOrder/payError/index')
            // this.$tools.navigateTo(-1)
          }
        })
        // #endif
        // #ifdef MP-ALIPAY
        // 处理支付
        const aliData = data.alipay
        if (
          data.payType === 'dceppay' &&
          data.payload.payload &&
          data.payload.payload.appid
        ) {
          uni.navigateToMiniProgram({
            appId: data.payload.payload.appid,
            path: data.payload.payload.path, //time的值为当前时间的time值
            extraData: {
              URL: encodeURI(data.payload.action) //包含接口参数的全链接
            },
            envVersion: data.payload.payload.envVersion, //develop开发版、trial体验版、release正式版
            success: (res) => {
              //成功跳转商户自行处理
              // this.goPaying()
              this.$emit('paySuccess')
            },
            fail: (err) => {
              console.log(err, 'err')
            }
          })
        } else if (
          data.payload &&
          (data.payload.method === 'POST' ||
            data.payload.method === 'REDIRECT') &&
          data.payload.action
        ) {
          if (
            data.payload.payload.length ||
            Object.keys(data.payload.payload).length
          ) {
            const payload = JSON.stringify(data.payload.payload)
            const url = `https://tkzc-release-cwap.zmaxfilm.com/webview.html?param=${payload}&action=${data.payload.action}&method=${data.payload.method}`
            this.$tools.navigateTo('/pages/webview/webview', { url })
          } else {
            this.$tools.navigateTo('/pages/webview/webview', {
              url: data.payload.actio
            })
          }
        } else {
          uni.requestPayment({
            orderInfo: aliData.trade_no,
            success: (res) => {
              if (res.resultCode === '6001') {
                this.$msg.toast('取消支付')
                const fromPath = this.$tools.getCurrentPage().fromPath
                if (fromPath === 'pagesOrder/sureOrder/index') {
                  uni.setStorageSync('payIndex', '1')
                  this.$tools.navigateTo(-1)
                } else if (fromPath === 'pagesOrder/goodsPay/index') {
                  console.log('取消支付')
                  this.$tools.navigateTo(
                    '/pagesOrder/order/detail',
                    {
                      orderId: data.orderId,
                      type: this.orderType
                    },
                    'redirectTo'
                  )
                } else if (fromPath === 'pagesOrder/order/detail') {
                  this.$tools.navigateTo(-1)
                } else {
                  this.$tools.navigateTo('/pagesOrder/order/detail', {
                    orderId: data.orderId,
                    type: this.orderType
                  })
                }
              } else if (
                res.resultCode === '9000' ||
                res.resultCode === '8000'
              ) {
                // 支付成功跳转
                console.log(res, 'res')
                this.$emit('paySuccess')
              } else {
                this.$msg.toast('支付失败', res)
                this.$tools.navigateTo('/pagesOrder/payError/index')
              }
            },
            fail: (err) => {
              this.$msg.toast('支付失败', err)
              this.$tools.navigateTo('/pagesOrder/payError/index')
              // this.$tools.navigateTo(-1)
            }
          })
        }
        // #endif
        // #ifdef MP-WEIXIN
        // 处理支付
        const wxData = data.weixinpay
        if (
          data.payType === 'dceppay' &&
          data.payload.payload &&
          data.payload.payload.appid
        ) {
          console.log(444444)
          uni.navigateToMiniProgram({
            appId: data.payload.payload.appid,
            path: data.payload.payload.path, //time的值为当前时间的time值
            extraData: {
              URL: encodeURI(data.payload.action) //包含接口参数的全链接
            },
            envVersion: data.payload.payload.envVersion, //develop开发版、trial体验版、release正式版
            success: (res) => {
              //成功跳转商户自行处理
              // this.goPaying()
              this.$emit('paySuccess')
            },
            fail: (err) => {
              console.log(err, 'err')
            }
          })
        } else if (
          data.payload &&
          (data.payload.method === 'POST' ||
            data.payload.method === 'REDIRECT') &&
          data.payload.action
        ) {
          if (
            data.payload.payload.length ||
            Object.keys(data.payload.payload).length
          ) {
            const payload = JSON.stringify(data.payload.payload)
            const url = `https://tkzc-release-cwap.zmaxfilm.com/webview.html?param=${payload}&action=${data.payload.action}&method=${data.payload.method}`
            this.$tools.navigateTo('/pages/webview/webview', { url })
          } else {
            this.$tools.navigateTo('/pages/webview/webview', {
              url: data.payload.action
            })
          }
        } else {
          uni.requestPayment({
            timeStamp: wxData.timeStamp,
            nonceStr: wxData.nonceStr,
            package: wxData.package,
            signType: wxData.signType,
            paySign: wxData.paySign,
            success: (res) => {
              // 支付成功跳转
              console.log(res, 'res')
              this.$emit('paySuccess')
            },
            fail: (err) => {
              if (err.errMsg.indexOf('cancel') === -1) {
                this.$msg.toast('支付失败')
                this.$tools.navigateTo('/pagesOrder/payError/index')
              } else {
                this.$msg.toast('取消支付')
                const fromPath = this.$tools.getCurrentPage().fromPath
                if (fromPath === 'pagesOrder/sureOrder/index') {
                  uni.setStorageSync('payIndex', '1')
                  this.$tools.navigateTo(-1)
                  // this.$tools.navigateTo('/pages/index/index', {}, 'switchTab')
                } else if (fromPath === 'pagesOrder/goodsPay/index') {
                  console.log('取消支付')
                  this.$tools.navigateTo(
                    '/pagesOrder/order/detail',
                    {
                      orderId: data.orderId,
                      type: this.orderType
                    },
                    'redirectTo'
                  )
                } else if (fromPath === 'pagesOrder/order/detail') {
                  this.$tools.navigateTo(-1)
                } else {
                  this.$tools.navigateTo('/pagesOrder/order/detail', {
                    orderId: data.orderId,
                    type: this.orderType
                  })
                }

                // this.$tools.navigateTo(-1)
              }
            }
          })
        }
        // #endif
        // #ifdef H5
        const payType = data.payType
        const type = data.type
        const d = data.payload
        // if (this.$auth.newABC()) {
        //   // 农行新支付
        //   const abcData = {
        //     tokenID: d.tokenID,
        //     backUrl: d.backURL
        //   }

        //   abcSdk.payment(abcData)
        //   return Promise.reject({ msg: '农行支付' })
        // }
        if (type === 'form') {
          // 网关支付
          if (d.method.toLocaleLowerCase() === 'redirect') {
            setTimeout(() => {
              window.location.href = d.action
            }, 200)
            return Promise.reject({ msg: '进行网关支付' })
          }
          this.$utils.submitForm(d.action, d.method, d.payload)
        } else if (type === 'sdk') {
          if (payType === 'weixinpay') {
            return wxSdk.wxPay(d)
          }
        }
        // #endif
        return Promise.reject({ myMsg: '没有合适的支付方式' })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .PayList {
    .title {
      font-size: 30rpx;
      font-weight: bold;
      height: 88rpx;
      line-height: 88rpx;
      border-bottom: 1px solid #eee;
    }
  }
</style>
